package servlets;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Termin;
import service.TerminplanerConnectionPool;
import service.TerminplanerService;

@WebServlet("/TerminplanerServlet")
public class TerminplanerServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    ArrayList<Termin> termine = null;
    Connection con = null;
    String calendarinput = request.getParameter("calendarinput");

    try {
      con = TerminplanerConnectionPool.getInstanz().getConnection();
      termine = TerminplanerService.getInstanz().getTermine(con);

      if (calendarinput != null && calendarinput != "") {
        Date calendarinputdate = TerminplanerService.getInstanz().parseStringtoDateWithoutTime(calendarinput);
        request.setAttribute("calendarinput", calendarinput);
        ArrayList<Termin> temp = termine;
        termine = new ArrayList<Termin>();

        for (Termin termin : temp) {
          Date terminAnfang = TerminplanerService.getInstanz().parseStringtoDateWithoutTime(
              termin.getFormattedTerminAnfang());
          Date terminEnde = TerminplanerService.getInstanz().parseStringtoDateWithoutTime(
              termin.getFormattedTerminEnde());

          if (!(terminAnfang.after(calendarinputdate) || terminEnde.before(calendarinputdate)))
            termine.add(termin);
        }
      }

    } catch (Exception e) {
      request.setAttribute("exception", e.getMessage());
      request.getRequestDispatcher("/WEB-INF/jsps/error.jsp").forward(request, response);
      e.printStackTrace();
      return;
    } finally {
      TerminplanerConnectionPool.getInstanz().saveClose(con);

    }

    if (termine != null) {
      request.setAttribute("termine", termine);
      request.getRequestDispatcher("/WEB-INF/jsps/terminplaner.jsp").forward(request, response);

    }

  }

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.sendRedirect("TerminplanerServlet");

  }

}
